﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace _064.CancellationToken2
{
	internal class Program
	{
		static async Task Main(string[] args)
		{
			CancellationTokenSource cts = new CancellationTokenSource();
			// 发出取消信号
			cts.CancelAfter(5000);
			CancellationToken token = cts.Token;
			await DownloadAsync3("https://www.baidu.com", 100, token);
		}

		/**
		 * 下载
		 */
		static async Task DownloadAsync(string url, int n,CancellationToken cancellationToken)
		{
			using (var client = new HttpClient())
			{
				for (int i = 0; i < n; i++)
				{
					string html = await client.GetStringAsync(url);
					Console.WriteLine($"{DateTime.Now}:{html}");
					// 判断是否取消
					if (cancellationToken.IsCancellationRequested)
					{
						Console.WriteLine("请求被取消");
						break;
					}
					// 请求取消 抛出异常
					cancellationToken.ThrowIfCancellationRequested();
				}
			}
		}
		static async Task DownloadAsync2(string url, int n, CancellationToken cancellationToken)
		{
			using (var client = new HttpClient())
			{
				for (int i = 0; i < n; i++)
				{
					string html = await client.GetStringAsync(url);
					Console.WriteLine($"{DateTime.Now}:{html}");
					// 请求取消 抛出异常
					cancellationToken.ThrowIfCancellationRequested();
				}
			}
		}

		static async Task DownloadAsync3(string url, int n, CancellationToken cancellationToken)
		{
			using (var client = new HttpClient())
			{
				for (int i = 0; i < n; i++)
				{
					// 内部处理 抛出异常处理
					var resp = await client.GetAsync(url,cancellationToken);
					string html = await resp.Content.ReadAsStringAsync();
					Console.WriteLine($"{DateTime.Now}:{html}");
				}
			}
		}
	}
}
